﻿using EmailClient.Model;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EmailClient.ViewModel
{
    class LogViewModel
    {
        public static async Task<ObservableCollection<Log>> GetList()
        {
            var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
            using (var db = dbFactory.Open())
            {
                return new ObservableCollection<Log>(await db.SelectAsync<Log>());
            }
        }

        public static async Task<ObservableCollection<Log>> GetList(EmailAccount account)
        {
            var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
            using (var db = dbFactory.Open())
            {
                var result = new ObservableCollection<Log>(await db.SelectAsync<Log>(x => x.AccountId == account.Id));                
                return result;
            }
        }

        public static async Task<Log> Get(int logId)
        {
            var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
            using (var db = dbFactory.Open())
            {
                var l = new List<Log>(await db.SelectAsync<Log>(x => x.Id == logId));
                return l.First<Log>();   
            }
        }

        public static async Task<string> InsertUpdate(Log item)
        {
            var result = "success";
            try
            {
                var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
                using (var db = dbFactory.Open())
                {
                    var isLetter = await db.SelectAsync<Letter>(x => x.Id == item.Id);
                    if (isLetter.Count > 0) await db.UpdateAsync(item);
                    else
                    {
                        await db.InsertAsync(item);                        
                    }
                }
            }
            catch (Exception e) { result = e.Message; }

            return result;
        }

        public static async Task<string> Delete(Log item)
        {
            var result = "success";
            try
            {
                var dbFactory = new OrmLiteConnectionFactory(App.DBPath, SqliteDialect.Provider, false);
                using (var db = dbFactory.Open())
                {
                    await db.DeleteAsync(item);
                }
            }
            catch (Exception e) { result = e.Message; }

            return result;
        }
    }
}
